<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <div style="float: left;">
        <el-form-item label="产线选择" prop="line_id">
          <el-select v-model="queryParams.line" multiple clearable collapse-tags placeholder="请选择产线"
            popper-class="custom-header" :max-collapse-tags="1" style="width: 200px" @change="updateCheckAllStatus">
            <el-checkbox style="margin-left: 10px;margin-bottom: 5px;" v-model="checkAll" :indeterminate="indeterminate"
              @change="handleCheckAll">
              All
            </el-checkbox>
            <el-option v-for="item in lineList" :key="item.line_id" :label="item.line_name" :value="item.line_id" />
          </el-select>

        </el-form-item>

        <el-form-item label="MPN" prop="MPN_name">
          <el-input v-model="queryParams.MPN_name" placeholder="请输入品目名称" clearable />
        </el-form-item>

        <el-form-item label="IE" prop="ie">
          <el-input v-model="queryParams.ie" placeholder="请输入IE" clearable />
        </el-form-item>

        <el-form-item label="测定日期" prop="query_time">
          <el-date-picker v-model="queryParams.query_time" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getCTList">搜索</el-button>
          <el-button type="primary" @click="resetButton">重置</el-button>
          <el-button type="warning" @click="handleExport">导出</el-button>
        </el-form-item>

      </div>


      <!-- 导入Excel -->
      <div style="float: left;">
        <el-upload action="" :auto-upload="false" :show-file-list="false" :on-change="handleImport" accept=".xlsx,.xls">
          <el-button type="warning">导入Excel</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件</div>
        </el-upload>

        <!-- 下载模板 -->
        <el-button type="text" @click="downloadTemplate">下载导入模板</el-button>
      </div>

      <div><el-checkbox v-model="checkHaveData" @change="getCTList">筛选有数据列</el-checkbox></div>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" height="720px" @row-dblclick="handleRowDblClick">
      <el-table-column v-if="false" label="编号" prop="mpn_id" align="center" height="150px" />
      <el-table-column label="序号" prop="serial_number" align="center" />
      <el-table-column v-if="false" label="ID" prop="ct_id" align="center" />
      <el-table-column label="品目名称" prop="mpn_name" align="center" />
      <el-table-column label="内部名称" prop="internal_name" align="center" width="180" />
      <el-table-column label="工程名称" prop="project_name" align="center" width="120" />
      <el-table-column label="工艺名称" prop="process_name" align="center" width="180" />
      <el-table-column label="基准CT" prop="benchmark_value" align="center" />
      <el-table-column label="测定日期" prop="enter_data" align="center" />
      <el-table-column v-for="(col, index) in dynamicColumns" :key="index" :label="`参数${index + 1}`" align="center"
        width="80">
        <template slot-scope="scope">
          <span :class="getColorClass(scope.row.benchmark_value, getValue(scope.row.test_values, index))">
            {{ getValue(scope.row.test_values, index) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="平均" align="center" width="80">
        <template slot-scope="scope">
          <span :class="getColorClass(scope.row.benchmark_value, getAVGValue(scope.row.test_values))">
            {{ getAVGValue(scope.row.test_values) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="异常原因" prop="exception_cause" align="center" width="180" />
      <el-table-column label="对策措施" prop="countermeasure" align="center" width="180" />
      <el-table-column label="纳期" prop="acceptance" align="center" />
      <el-table-column label="负责人" prop="npi" align="center" />
      <el-table-column label="Process" prop="process" align="center" width="120" />
      <el-table-column label="IE" prop="ie" align="center" width="120" />
      <el-table-column label="负荷表组合名称" prop="ic_name" align="center" width="180" />
      <el-table-column label="DFF" prop="dff" align="center" />
      <el-table-column label="psc/sheet" prop="psc_sheet" align="center" />
      <el-table-column label="设备配置" prop="device_config" align="center" />
      <el-table-column label="Line NO" prop="line_name" align="center" />
      <el-table-column label="部门" prop="dept_name" align="center" />
      <el-table-column label="课别" prop="class_name" align="center" />
      <el-table-column label="楼层" prop="floor" align="center" />
      <el-table-column label="BU" prop="bu" align="center" />
      <el-table-column label="DFF" align="center" width="180">
        <template slot-scope="scope">
          {{ scope.row.internal_name + "" + scope.row.process }}
        </template>
      </el-table-column>
      <el-table-column label="对碰名称" align="center" width="180">
        <template slot-scope="scope">
          {{ scope.row.internal_name + "" + scope.row.ie }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="80">
        <template #default="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      :page-sizes="pageSizes" @pagination="getCTList" />


    <!-- 新增/修改界面 -->
    <el-dialog :title="title" :visible.sync="dialogVisibleCTform" width="30%" :before-close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="品目id" prop="MPN_Id" v-show="false" disabled>
          <el-input v-model="form.mpn_id" />
        </el-form-item>
        <el-form-item label="品目名称" prop="mpn_name">
          <el-input v-model="form.mpn_name" placeholder="请输入品目名称" disabled />
        </el-form-item>
        <el-form-item label="内部名称" prop="internal_name">
          <el-input v-model="form.internal_name" placeholder="请输入内部名称" disabled />
        </el-form-item>
        <el-form-item label="工程名称" prop="project_name">
          <el-input v-model="form.project_name" placeholder="请输入工程名称" disabled />
        </el-form-item>
        <el-form-item label="工艺名称" prop="process_name">
          <el-input v-model="form.process_name" placeholder="请输入工艺名称" disabled />
        </el-form-item>
        <el-form-item label="产线" prop="line_name">
          <el-input v-model="form.line_name" disabled />
        </el-form-item>
        <el-form-item label="基准CT" prop="benchmark_value">
          <el-input v-model="form.benchmark_value" placeholder="请输入基准CT" disabled />
        </el-form-item>
        <el-form-item v-for="index in 10" :key="index" :label="`参数${index}`" :prop="`test_values${index}`">
          <el-input v-model="form.test_values[index - 1]" :placeholder="`参数${index}`"
            @blur="calculateExpression(index - 1)" />
        </el-form-item>
        <el-form-item label="测定日期" prop="enter_data">
          <el-date-picker v-model="form.enter_data" type="date" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="异常原因" prop="exception_cause">
          <el-input v-model="form.exception_cause" placeholder="请输入异常原因" />
        </el-form-item>
        <el-form-item label="对策措施" prop="countermeasure">
          <el-input v-model="form.countermeasure" placeholder="请输入对策措施" />
        </el-form-item>
        <el-form-item label="纳期" prop="acceptance">
          <el-date-picker v-model="form.acceptance" type="date" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="负责人" prop="npi">
          <el-input v-model="form.npi" placeholder="请输入NPI" />
        </el-form-item>
        <el-form-item label="Process" prop="process">
          <el-input v-model="form.process" placeholder="请输入process" disabled />
        </el-form-item>
        <el-form-item label="IE" prop="ie">
          <el-input v-model="form.ie" placeholder="请输入ie" disabled />
        </el-form-item>
        <el-form-item label="负荷表组合名称" prop="ic_name">
          <el-input v-model="form.ic_name" placeholder="请输入负荷表组合名称" disabled />
        </el-form-item>
        <el-form-item label="制品长度" prop="DFF">
          <el-input v-model="form.dff" placeholder="请输入制品长度" disabled />
        </el-form-item>
        <el-form-item label="psc/sheet" prop="psc_sheet">
          <el-input v-model="form.psc_sheet" placeholder="请输入psc/sheet" disabled />
        </el-form-item>
        <el-form-item label="设备配置" prop="device_config">
          <el-input v-model="form.device_config" placeholder="请输入设备配置" disabled />
        </el-form-item>
        <el-form-item label="部门" prop="dept_name">
          <el-input v-model="form.dept_name" placeholder="请输入部门" disabled />
        </el-form-item>
        <el-form-item label="课别" prop="class_name">
          <el-input v-model="form.class_name" placeholder="请输入课别" disabled />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="form.floor" placeholder="请输入楼层" disabled />
        </el-form-item>
        <el-form-item label="BU" prop="bu">
          <el-input v-model="form.bu" placeholder="请输入BU" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { getUserLinkLineByLogin, getCTTableByLineIdEnterDateMPNName, getCTTableByCTId, getCTTableByLineIdEnterDateMPNNameHaveData, setCTtable, ctExport, importctExcel, exportctTemplate, delct } from "@/api/ctManage/MPNManage"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "sampleDel",
  components: { Treeselect },
  data() {
    return {
      checkHaveData: false,
      form: {
        test_values: []
      },
      dialogVisibleCTform: false,
      // 新增全选状态变量
      checkAll: false,         // 全选状态
      indeterminate: false,    // 半选状态
      //产线参数
      lineList: [],
      //测试参数初始化列表
      dynamicColumns: Array(10).fill({}),
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        MPN_name: '',
        ie: '',
        query_time: [],
        line: []   // 确保初始化为数组
      },
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      dialogVisible: false,

      pageSizes: [10, 20, 50, 100, 200],
      // 表单验证规则
      rules: {
        internal_name: [
          { required: true, message: "内部名称不能为空", trigger: "blur" },
        ],
        project_name: [
          { required: true, message: "工程名称不能为空", trigger: "blur" },
        ],
        process_name: [
          { required: true, message: "工艺名称不能为空", trigger: "blur" },
        ],
        mpn_name: [
          { required: true, message: "品目名不能为空", trigger: "blur" },
        ],
        line: [
          { required: true, message: "请选择产线", trigger: "blur" },
        ],
        benchmark_value: [
          { required: true, message: "基准CT不能为空", trigger: "blur" },
          { pattern: /^\d*\.?\d*$/, message: '只能输入数字和小数点', trigger: 'blur' }
        ],
        process: [
          { required: true, message: "process不能为空", trigger: "blur" },
        ],
        ie: [
          { required: true, message: "IE不能为空", trigger: "blur" },
        ],
        ic_name: [
          { required: true, message: "组合名称不能为空", trigger: "blur" },
        ],
        psc_sheet: [
          { pattern: /^\d*\.?\d*$/, message: '只能输入数字和小数点', trigger: 'blur' }
        ]
      },
    };
  },
  created() {
    this.getUserLine()
  },
  methods: {
    calculateExpression(index) {
      try {
        // 安全过滤 - 只允许数字、基本运算符和括号
        const safeExpression = this.form.test_values[index]
          .replace(/[^0-9+\-*/().]/g, '');

        // 使用 Function 构造函数比 eval 更安全
        const result = new Function('return ' + safeExpression)();

        // 更新值为计算结果
        this.$set(this.form.test_values, index, result.toString());
        if (this.form.benchmark_value < Number(result.toString())) {
          this.$message.error("大于基准CT，请输入对策原因");
        }
      } catch (e) {
        // 计算失败保持原值
        console.warn('计算失败:', e);
      }
    },
    // 获取颜色类名
    getColorClass(benchmark, currentValue) {
      if (currentValue === '--' || benchmark === null || benchmark === undefined) {
        return '';
      }


      if (Number(benchmark) > Number(currentValue)) {
        return 'normal-color';
      } else {
        return 'danger-color';
      }
    },
    //excel使用
    handleExport() {
      this.$confirm("确认导出CT数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 调用导出接口
        ctExport().then(response => {
          const url = URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', 'ct.xlsx');
          document.body.appendChild(link);
          link.click();
        });
      });
    },
    //关闭按钮
    cancel() {
      this.dialogVisibleCTform = false;
      this.getCTList();
    },
    // 双击行处理方法
    handleRowDblClick(row, column, event) {
      this.handleAdd(row, '修改');
    },
    // 新增按钮
    handleAdd(data, title) {
      this.dialogVisibleCTform = true;
      // 清空表单
      this.form = data;
      if (data.enter_data == '') {
        this.form.enter_data = new Date().toISOString().split('T')[0];
      }
      this.title = title;
    },
    //获取平均值
    getAVGValue(values) {
      var addvalues = 0.0;
      for (let index = 0; index < values.length; index++) {
        addvalues += Number(values[index])
      }
      return Number(addvalues / values.length).toFixed(2);

    },
    //获取当前登录用户链接的全部产线
    getUserLine() {
      getUserLinkLineByLogin().then(response => {
        this.lineList = response;
        // 初始化全选状态
        this.updateCheckAllStatus();
        if (this.$route.query.ct_id) {
          getCTTableByCTId(this.$route.query.ct_id).then(response => {
            this.tableData = [];
            for (let index = 0; index < response.length; index++) {
              const element = response[index];
              this.tableData.push({
                serial_number: index + 1,
                ct_id: element.ct_id,
                mpn_name: element.mpn_name,
                internal_name: element.internal_name,
                project_name: element.project_name,
                process_name: element.process_name,
                line_name: element.line.line_name,
                mpn_id: element.mpn_id,
                benchmark_value: element.benchmark_value,
                enter_data: element.enter_data,
                test_values: this.testValues(element.test_values),
                exception_cause: element.exception_cause,
                countermeasure: element.countermeasure,
                acceptance: element.acceptance,
                process: element.process,
                ic_name: element.ic_name,
                psc_sheet: element.psc_sheet,
                device_config: element.device_config,
                state: element.state,
                dept_name: element.dept_name,
                class_name: element.class_name,
                floor: element.floor,
                npi: element.npi,
                dff: element.dff,
                ie: element.ie,
                bu: element.bu
              })
            }
          })
        }
      })
    },
    //获取测试用的值
    getValue(values, index) {
      if (!values || index >= values.length) return '--';
      // 保留两位小数
      return Number(values[index]).toFixed(2);
    },
    //查询样本
    getCTbyId() {
      getCTTableByLineIdEnterDateMPNNameHaveData(this.queryParams.pageNum, this.queryParams.pageSize, this.queryParams.MPN_name, this.queryParams.ie, this.queryParams.line, this.queryParams.query_time[0], this.queryParams.query_time[1]).then(response => {
        this.tableData = [];
        this.total = response.total;
        for (let index = 0; index < response.list.length; index++) {
          const element = response.list[index];
          this.tableData.push({
            serial_number: index + 1,
            ct_id: element.ct_id,
            mpn_name: element.mpn_name,
            internal_name: element.internal_name,
            project_name: element.project_name,
            process_name: element.process_name,
            line_name: element.line.line_name,
            mpn_id: element.mpn_id,
            benchmark_value: element.benchmark_value,
            enter_data: element.enter_data,
            test_values: this.testValues(element.test_values),
            exception_cause: element.exception_cause,
            countermeasure: element.countermeasure,
            acceptance: element.acceptance,
            process: element.process,
            ic_name: element.ic_name,
            psc_sheet: element.psc_sheet,
            device_config: element.device_config,
            state: element.state,
            dept_name: element.dept_name,
            class_name: element.class_name,
            floor: element.floor,
            npi: element.npi,
            dff: element.dff,
            ie: element.ie,
            bu: element.bu
          })
        }
      })
    },
    //查询样本
    getCTList() {
      if (this.checkHaveData) {
        getCTTableByLineIdEnterDateMPNNameHaveData(this.queryParams.pageNum, this.queryParams.pageSize, this.queryParams.MPN_name, this.queryParams.ie, this.queryParams.line, this.queryParams.query_time[0], this.queryParams.query_time[1]).then(response => {
          this.tableData = [];
          this.total = response.total;
          for (let index = 0; index < response.list.length; index++) {
            const element = response.list[index];
            this.tableData.push({
              serial_number: index + 1,
              ct_id: element.ct_id,
              mpn_name: element.mpn_name,
              internal_name: element.internal_name,
              project_name: element.project_name,
              process_name: element.process_name,
              line_name: element.line.line_name,
              mpn_id: element.mpn_id,
              benchmark_value: element.benchmark_value,
              enter_data: element.enter_data,
              test_values: this.testValues(element.test_values),
              exception_cause: element.exception_cause,
              countermeasure: element.countermeasure,
              acceptance: element.acceptance,
              process: element.process,
              ic_name: element.ic_name,
              psc_sheet: element.psc_sheet,
              device_config: element.device_config,
              state: element.state,
              dept_name: element.dept_name,
              class_name: element.class_name,
              floor: element.floor,
              npi: element.npi,
              dff: element.dff,
              ie: element.ie,
              bu: element.bu
            })
          }
        })
      } else {
        getCTTableByLineIdEnterDateMPNName(this.queryParams.pageNum, this.queryParams.pageSize, this.queryParams.MPN_name, this.queryParams.ie, this.queryParams.line, this.queryParams.query_time[0], this.queryParams.query_time[1]).then(response => {
          this.tableData = [];
          this.total = response.total;
          for (let index = 0; index < response.list.length; index++) {
            const element = response.list[index];
            this.tableData.push({
              serial_number: index + 1,
              ct_id: element.ct_id,
              mpn_name: element.mpn_name,
              internal_name: element.internal_name,
              project_name: element.project_name,
              process_name: element.process_name,
              line_name: element.line.line_name,
              mpn_id: element.mpn_id,
              benchmark_value: element.benchmark_value,
              enter_data: element.enter_data,
              test_values: this.testValues(element.test_values),
              exception_cause: element.exception_cause,
              countermeasure: element.countermeasure,
              acceptance: element.acceptance,
              process: element.process,
              ic_name: element.ic_name,
              psc_sheet: element.psc_sheet,
              device_config: element.device_config,
              state: element.state,
              dept_name: element.dept_name,
              class_name: element.class_name,
              floor: element.floor,
              npi: element.npi,
              dff: element.dff,
              ie: element.ie,
              bu: element.bu
            })
          }
        })
      }


    },
    //测试数值初始化
    testValues(value) {
      if (value != "") {
        return JSON.parse(value);
      } else {
        return []
      }
    },
    //重置
    resetButton() {
      this.queryParams.MPN_name = '',
        this.queryParams.query_time = [],
        this.queryParams.line = []
    },
    // 编辑按钮
    handleEdit(row) {
      this.resetForm();
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = "修改样本";
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('确认删除该样本？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delct(row.ct_id).then(response => {
            if (response > 0) {
              this.$message.success("删除成功");
              this.getCTList();
            } else {
              this.$message.success("删除失败");
            }
          })
        })
        .catch(() => { });
    },
    // 表单提交
    submitForm() {
      this.$refs["form"].validate((valid) => {
        var state;
        if (this.form.ct_id > 0) {
          state = '修改'
        } else {
          state = '添加'
        }
        if (valid) {
          setCTtable(this.form).then(response => {
            if (response > 0) {
              this.$message.success(state + "成功");
              this.getCTList();
            } else {
              this.$message.error(state + "失败");
            }
          })
          this.dialogVisibleCTform = false;
        }
      });
    },
    // 新增：全选处理函数
    handleCheckAll(val) {
      // val: 全选复选框的当前状态 (true/false)
      if (val) {
        // 全选：将所有产线ID加入数组
        this.queryParams.line = this.lineList.map(item => item.line_id);
      } else {
        // 取消全选：清空数组
        this.queryParams.line = [];
      }
      // 取消半选状态
      this.indeterminate = false;
    },

    // 新增：更新全选状态
    updateCheckAllStatus() {
      const selectedCount = this.queryParams.line.length;
      const totalCount = this.lineList.length;

      // 更新全选状态
      this.checkAll = selectedCount === totalCount && totalCount > 0;
      // 更新半选状态（部分选择时）
      this.indeterminate = selectedCount > 0 && selectedCount < totalCount;
    },
    //导入
    handleImport(file) {
      const formData = new FormData();
      formData.append("file", file.raw);
      importctExcel(formData).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.getCTList();
      }).catch(error => {
        this.$modal.msgError(error);
      });
    },

    //导入模板
    downloadTemplate() {
      exportctTemplate().then(res => {
        // 处理blob下载
        const blob = new Blob([res], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = '数据导入模板.xlsx';
        link.click();
      });

    }
  },

  mounted() {
  }
};
</script>

<style scoped>
/* 表格滚动条样式 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 12px;
  /* 纵向滚动条宽度 */
  height: 12px;
  /* 横向滚动条高度 */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  /* 滚动条滑块颜色 */
  border-radius: 4px;
  /* 滚动条滑块圆角 */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
  /* 鼠标悬停时滚动条滑块颜色 */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: #f5f5f5;
  /* 滚动条轨道颜色 */
  border-radius: 4px;
  /* 滚动条轨道圆角 */
}

.ml10 {
  margin-left: 10px;
}

.normal-color {
  color: #67C23A;
  /* 绿色 - 正常 */
}

.warning-color {
  color: #E6A23C;
  /* 黄色 - 警告 */
}

.danger-color {
  color: #F56C6C;
  /* 红色 - 危险 */
}

/* 状态样式 */
.status-normal {
  color: #67C23A;
  background: #f0f9eb;
  padding: 5px 10px;
  border-radius: 4px;
  display: inline-block;
}

.status-warning {
  color: #E6A23C;
  background: #fdf6ec;
  padding: 5px 10px;
  border-radius: 4px;
  display: inline-block;
}

.status-expired {
  color: #F56C6C;
  background: #fef0f0;
  padding: 5px 10px;
  border-radius: 4px;
  display: inline-block;
}
</style>
